<template>
  <div class="app-container">
    <el-button-group style="margin-bottom: 16px;">
      <el-button @click="goTo('/content/announcement')">公告管理</el-button>
      <el-button @click="goTo('/content/help')">帮助中心</el-button>
      <el-button @click="goTo('/permission/role')">角色管理</el-button>
      <el-button @click="goTo('/system/basic')">系统配置</el-button>
    </el-button-group>
    <!-- 搜索和操作栏 -->
    <div class="filter-container">
      <el-input v-model="queryParams.title" placeholder="轮播图标题" clearable class="filter-item" style="width: 200px;" @keyup.enter="handleQuery" />
      
      <el-select v-model="queryParams.status" placeholder="状态" clearable class="filter-item" style="width: 120px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      
      <el-select v-model="queryParams.position" placeholder="展示位置" clearable class="filter-item" style="width: 120px;">
        <el-option v-for="item in positionOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      
      <el-button type="primary" class="filter-item" @click="handleQuery">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button type="success" class="filter-item" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="carouselList"
      border
      style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" />
      <el-table-column label="标题" prop="title" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="图片" width="120" align="center">
        <template #default="{ row }">
          <el-image
            style="width: 80px; height: 40px"
            :src="row.imageUrl"
            :preview-src-list="[row.imageUrl]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="链接" prop="linkUrl" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="展示位置" prop="position" width="120">
        <template #default="{ row }">
          <el-tag :type="getPositionTagType(row.position)">
            {{ getPositionName(row.position) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getPeriodStatusTag(row)">{{ getPeriodStatus(row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" prop="startTime" width="160">
        <template #default="{ row }">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" prop="endTime" width="160">
        <template #default="{ row }">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="row.status === 'active' ? 'warning' : 'success'" 
            @click="handleToggleStatus(row)">
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination-container"
    />

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="360px">
      <div>确定要删除该轮播图吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { carouselApi } from '@/api/content'
import type { Carousel } from '@/types'

const router = useRouter()
const loading = ref(false)
const carouselList = ref<Carousel[]>([])
const total = ref(0)
const deleteDialogVisible = ref(false)
const deleteId = ref('')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  title: '',
  status: '',
  position: ''
})

// 状态选项
const statusOptions = [
  { value: 'active', label: '启用' },
  { value: 'inactive', label: '禁用' }
]

// 展示位置选项
const positionOptions = [
  { value: 'home', label: '首页' },
  { value: 'product', label: '商品页' },
  { value: 'category', label: '分类页' },
  { value: 'activity', label: '活动页' }
]

// 获取展示位置名称
const getPositionName = (position: string) => {
  const found = positionOptions.find(item => item.value === position)
  return found ? found.label : '未知位置'
}

// 获取展示位置标签类型
const getPositionTagType = (position: string) => {
  const map: Record<string, string> = {
    home: 'primary',
    product: 'success',
    category: 'warning',
    activity: 'danger'
  }
  return map[position] || 'info'
}

// 查询轮播图列表
const getList = async () => {
  loading.value = true
  try {
    const res = await carouselApi.getList(queryParams)
    carouselList.value = res.list
    total.value = res.total
  } catch (e) {
    ElMessage.error('获取轮播图失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 添加轮播图
const handleAdd = () => {
  router.push('/content/carousel/add')
}

// 编辑轮播图
const handleUpdate = (row: Carousel) => {
  router.push(`/content/carousel/edit/${row.id}`)
}

// 切换状态
const handleToggleStatus = (row: Carousel) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const statusText = newStatus === 'active' ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}该轮播图吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里可以调用实际的API
      // await carouselApi.updateStatus(row.id, newStatus)
      
      // 模拟更新
      const index = carouselList.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        carouselList.value[index].status = newStatus
      }
      
      ElMessage.success(`${statusText}成功`)
    } catch (error) {
      console.error(`${statusText}轮播图失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }).catch(() => {})
}

// 删除轮播图
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', { type: 'warning' })
    await carouselApi.delete({ id: row.id })
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

// 确认删除
const confirmDelete = async () => {
  try {
    // 这里可以调用实际的API
    // await carouselApi.delete(deleteId.value)
    
    // 模拟删除
    carouselList.value = carouselList.value.filter(item => item.id !== deleteId.value)
    total.value--
    
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
  } catch (error) {
    console.error('删除轮播图失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  getList()
}

// 生命周期
onMounted(() => {
  getList()
})

const formatDate = (date: string) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const getPeriodStatus = (row: Carousel) => {
  const now = new Date().getTime()
  const start = row.startTime ? new Date(row.startTime).getTime() : 0
  const end = row.endTime ? new Date(row.endTime).getTime() : 0
  if (start && now < start) return '未开始'
  if (end && now > end) return '已结束'
  return '进行中'
}

const getPeriodStatusTag = (row: Carousel) => {
  const status = getPeriodStatus(row)
  if (status === '未开始') return 'info'
  if (status === '已结束') return 'danger'
  return 'success'
}

const goTo = (path: string) => router.push(path)
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 